package com.hefan.api.controller.dynamic;

import com.alibaba.fastjson.JSON;
import com.cat.common.entity.Page;
import com.cat.common.entity.ResultBean;
import com.cat.common.meta.ResultCode;
import com.cat.common.meta.UserTypeEnum;
import com.google.common.collect.Maps;
import com.hefan.api.service.DynamicLocalService;
import com.hefan.api.service.UserLocalService;
import com.hefan.api.service.WatchLocalService;
import com.hefan.api.service.live.LiveRoomLocalService;
import com.hefan.club.dynamic.bean.DynamicAlbum;
import com.hefan.club.dynamic.bean.Message;
import com.hefan.club.dynamic.bean.MessageConstant;
import com.hefan.common.util.HttpUtils;
import com.hefan.common.util.MapUtils;
import com.hefan.live.bean.LiveRoom;
import com.hefan.live.bean.LivingRoomInfoVo;
import com.hefan.user.bean.WebUser;
import org.jsoup.helper.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * 动态
 *
 * @author wangpengyan
 */
@Controller
@RequestMapping("/v1/message")
public class DynamicController {
  public static Logger logger = LoggerFactory.getLogger(DynamicController.class);

  @Autowired
  private DynamicLocalService dynamicLocalService;
  @Autowired
  private UserLocalService userLocalService;
  @Autowired
  private LiveRoomLocalService liveRoomLocalService;
  @Resource
  private WatchLocalService watchLocalService;

/*    private static final String LISTMESSAGE = "list_message";
    private static final int LIST_MESSAGE_CACHE_TIME = 30 * 60;
    private static final int FIRSTPAGE = 1;*/

  /**
   * 主播所有视频
   *
   * @param po
   * @return
   * @throws Exception
   */
  @ResponseBody
  @RequestMapping("/listAnchorClubVideos")
  public String listAnchorClubVideos(HttpServletRequest req, Page po) {
    ResultBean resultBean = new ResultBean();
    // 取值
    try {
      Map map = HttpUtils.initParam(req, Map.class);

      String userId = MapUtils.getStrValue(map,"userId","");
      String authorId = MapUtils.getStrValue(map,"authorId","");
      int pageNo = MapUtils.getIntValue(map,"pageNo",1);
      // 逻辑开始
      if (StringUtil.isBlank(authorId) || StringUtil.isBlank(userId)) {
        resultBean.setMsg("authorId or userId is null");
        resultBean.setCode(ResultCode.UNSUCCESS.get_code());
        return JSON.toJSONString(resultBean);
      }
      po.setPageNo(pageNo);

      resultBean.setData(dynamicLocalService.videoList(po, userId, String.valueOf(MessageConstant.ISSYNC), authorId));
      resultBean.setCode(ResultCode.SUCCESS.get_code());
    } catch (Exception e) {
      resultBean.setCode(ResultCode.UNSUCCESS.get_code());
      logger.error("获取主播所有视频失败", e);
    }

    return JSON.toJSONString(resultBean);
  }

  /**
   * 删除动态
   *
   * @return
   */
  @ResponseBody
  @RequestMapping("/deleteMessage")
  public ResultBean deleteMessage(HttpServletRequest req) {
    // 取值
    Message mes = new Message();
    ResultBean result = new ResultBean();
    Map map = HttpUtils.initParam(req, Map.class);
    try {

      String userId = MapUtils.getStrValue(map,"userId","");
      String messageId = MapUtils.getStrValue(map,"messageId","");
      String messageType = MapUtils.getStrValue(map,"messageType","");

      if (StringUtils.isEmpty(userId)) {
        result.setCode(ResultCode.UNSUCCESS.get_code());
        result.setMsg("userId is null");
        return result;
      }
      if (StringUtils.isEmpty(messageId)) {
        result.setCode(ResultCode.UNSUCCESS.get_code());
        result.setMsg("messageId is null");
        return result;
      }

      if (StringUtils.isEmpty(messageType)) {
        result.setCode(ResultCode.UNSUCCESS.get_code());
        result.setMsg("messageType is null");
        return result;
      }

      mes.setMessageId(Integer.valueOf(messageId));
      mes.setMessageType(messageType);
      mes.setUserId(userId);

      result = dynamicLocalService.deleteMessage(mes);
    } catch (Exception e) {
      result.setCode(ResultCode.UNSUCCESS.get_code());
      logger.error("删除失败", e);
    }
    return result;

  }

  /**
   * 查询关注人的微博
   *
   * @param po
   * @return
   */
  @RequestMapping("/listClubIndex")
  @ResponseBody
  public String listClubIndex(Page po, HttpServletRequest req) {
    ResultBean resultBean = new ResultBean();
    // start
    try {

      Map map = HttpUtils.initParam(req, Map.class);
      String userId = MapUtils.getStrValue(map,"userId","");
      int pageNo = MapUtils.getIntValue(map,"pageNo",1);
      // end
      if (StringUtil.isBlank(userId)) {
        resultBean.setCode(ResultCode.UNSUCCESS.get_code());
        resultBean.setMsg("userId is null");
        return JSON.toJSONString(resultBean);
      }
       po.setPageNo(pageNo);
      resultBean.setCode(ResultCode.SUCCESS.get_code());
      resultBean.setData(dynamicLocalService.listClubIndex(po, userId));
      resultBean.setMsg(ResultCode.SUCCESS.getMsg());
    } catch (Exception e) {
      resultBean.setCode(ResultCode.UNSUCCESS.get_code());
      logger.error("删除失败", e);
    }
    return JSON.toJSONString(resultBean);
  }

  /**
   * 查询主播所有微博
   *
   * @param po
   * @return
   */
  @RequestMapping("/listMessage")
  @ResponseBody
  public String listMessage(Page po, HttpServletRequest req) {
    // start
    ResultBean resultBean = new ResultBean();
    Map map = HttpUtils.initParam(req, Map.class);
    try {
      String userId = MapUtils.getStrValue(map,"userId","");
      int pageNo = MapUtils.getIntValue(map,"pageNo",1);
      String authorId =  MapUtils.getStrValue(map,"authorId","");

      // end
      if (StringUtil.isBlank(authorId) || StringUtil.isBlank(userId)) {
        resultBean.setMsg("authorId or userId is null");
        resultBean.setCode(ResultCode.UNSUCCESS.get_code());
        return JSON.toJSONString(resultBean);
      }
      po.setPageNo(pageNo);
      logger.info("用户userId={}查看用户userId={}的俱乐部,pageNo={},pageSize={}", userId, authorId, po.getPageNo(), po.getPageSize());
      resultBean.setCode(ResultCode.SUCCESS.get_code());
      resultBean.setData(dynamicLocalService.listMessage(po, userId, authorId));
      resultBean.setMsg(ResultCode.SUCCESS.getMsg());
    } catch (Exception e) {
      // TODO: handle exception
      resultBean.setCode(ResultCode.UNSUCCESS.get_code());
      logger.error("主播俱乐部信息获取失败");
    }
    return JSON.toJSONString(resultBean);
  }

  /**
   * 置顶
   *
   * @return
   * @throws Exception
   */
  @ResponseBody
  @RequestMapping("/topMessage")
  public synchronized String top(HttpServletRequest req) throws Exception {
    ResultBean resultBean = new ResultBean();
    // start
    Map map = HttpUtils.initParam(req, Map.class);
    try {
      String userId = MapUtils.getStrValue(map,"userId","");
      String messageId =  MapUtils.getStrValue(map,"messageId","");

      if (StringUtil.isBlank(messageId) || StringUtil.isBlank(userId)) {
        resultBean.setMsg("messageId or userId is null");
        resultBean.setCode(ResultCode.UNSUCCESS.get_code());
        return JSON.toJSONString(resultBean);
      }

      resultBean = dynamicLocalService.top(userId, messageId);
    } catch (Exception e) {
      resultBean.setCode(ResultCode.UNSUCCESS.get_code());
      logger.error("置頂失败");
    }
    return  JSON.toJSONString(resultBean);
  }

  /**
   * 取消置顶
   *
   * @return
   */
  @ResponseBody
  @RequestMapping("/unTop")
  public synchronized String unTop(HttpServletRequest req) {
    ResultBean resultBean = new ResultBean();

    try {
      Map map = HttpUtils.initParam(req, Map.class);

      String userId = MapUtils.getStrValue(map,"userId","");
      String messageId =  MapUtils.getStrValue(map,"messageId","");

      if (StringUtil.isBlank(messageId) || StringUtil.isBlank(userId)) {
        resultBean.setMsg("messageId or userId is null");
        resultBean.setCode(ResultCode.UNSUCCESS.get_code());
        return JSON.toJSONString(resultBean);
      }
      if (dynamicLocalService.unTop(userId, messageId) > 0) {
        resultBean.setCode(ResultCode.SUCCESS.get_code());
        resultBean.setMsg("取消置顶成功");
      } else {
        resultBean.setCode(ResultCode.UNSUCCESS.get_code());
        resultBean.setMsg("取消置顶失败");
      }
    } catch (Exception e) {
      resultBean.setCode(ResultCode.UNSUCCESS.get_code());
      resultBean.setMsg("取消置顶失败");
    }

    return JSON.toJSONString(resultBean);
  }

  /**
   * 查询图片
   *
   * @param po
   * @return
   */
  @ResponseBody
  @RequestMapping("/listAnchorClubPhotos")
  public String photoList(HttpServletRequest req, Page po) {
    ResultBean resultBean = new ResultBean();
    try {
      // start
      Map<String, Object> map = HttpUtils.initParam(req, Map.class);

      String userId = MapUtils.getStrValue(map,"userId","");
      int pageNo =  MapUtils.getIntValue(map,"pageNo",1);

      logger.info("查询用户userId={}图片列表，参数pageNo={}", userId, pageNo);
      if (StringUtil.isBlank(userId)) {
        resultBean.setMsg("userId is null");
        resultBean.setCode(ResultCode.UNSUCCESS.get_code());
        return JSON.toJSONString(resultBean);
      }
      po.setPageNo(pageNo);
      resultBean.setCode(ResultCode.SUCCESS.get_code());
      resultBean.setData(dynamicLocalService.photoList(po, String.valueOf(MessageConstant.ISSYNC), userId, null));
      resultBean.setMsg(ResultCode.SUCCESS.getMsg());
    } catch (Exception e) {
      resultBean.setCode(ResultCode.UNSUCCESS.get_code());
      logger.error("图片获取失败", e);
    }

    return JSON.toJSONString(resultBean);
  }

  /**
   * 点赞
   *
   * @return
   */
  @ResponseBody
  @RequestMapping("/admire")
  public String admire(HttpServletRequest req) {
    ResultBean resultBean = new ResultBean();
    try {
      // start
      Map map = HttpUtils.initParam(req, Map.class);
      String userId = MapUtils.getStrValue(map,"userId","");
      String messageId = MapUtils.getStrValue(map,"messageId","");

      // end
      if (StringUtil.isBlank(messageId)||StringUtil.isBlank(userId)) {
        resultBean.setMsg("userId or messageId is null");
        resultBean.setCode(ResultCode.UNSUCCESS.get_code());
        return JSON.toJSONString(resultBean);
      }

      if (dynamicLocalService.admireMsg(userId, messageId) > 0) {
        resultBean.setMsg(ResultCode.SUCCESS.getMsg());
        resultBean.setCode(ResultCode.SUCCESS.get_code());
      } else {
        resultBean.setCode(ResultCode.UNSUCCESS.get_code());
      }
    } catch (Exception e) {
      resultBean.setCode(ResultCode.UNSUCCESS.get_code());
      logger.error("点赞失败", e);
    }
    return JSON.toJSONString(resultBean);
  }

  /**
   * 发布动态
   *
   * @param message
   * @param request
   * @return
   */
  @ResponseBody
  @RequestMapping("/insertMessage")
  public String insertMessage(HttpServletRequest request) {
    Message message = HttpUtils.initParam(request, Message.class);
    ResultBean resultBean = null;
    try {
      if(message==null){
        resultBean = new ResultBean(ResultCode.ParamException);
        return JSON.toJSONString(resultBean);
      }
      if ("2".equals(message.getMessageType())){
        message.setPath(message.getPath().replaceAll("img.hefantv.com", "img1.hefantv.com"));
      }

      if ("3".equals(message.getMessageType())){
        message.setBackImg(message.getBackImg().replaceAll("vod.hefantv.com", "vodpic.hefantv.com"));
      }

      //查询发送人基本信息
      WebUser webUser = userLocalService.getWebUserByUserId(message.getUserId());
      if (webUser == null) {
        resultBean = new ResultBean(ResultCode.LoginUserIsNotExist);
        return JSON.toJSONString(resultBean);
      }
      // 是否主播
      if (!UserTypeEnum.isAnchor(webUser.getUserType())) {
        //查询当日发放动态数
        boolean result = dynamicLocalService.isSendMessage(message.getUserId());
        if (!result) {
          logger.error("用户userId={}发送动态已达上限", message.getUserId());
          return JSON.toJSONString(new ResultBean(ResultCode.MessageUpperLimit));
        }
      }
      logger.info("用户发送动态内容={}", JSON.toJSONString(message));
      resultBean = dynamicLocalService.insertMessage(message);
      return JSON.toJSONString(resultBean);
    } catch (Exception e) {
      e.printStackTrace();
      resultBean = new ResultBean(ResultCode.UNSUCCESS);
    }
    return JSON.toJSONString(resultBean);
  }

  /**
   * 视频水印回调,@Deprecated 20170327王超后端直接更新数据库
   *
   * @param jobId
   * @param req
   * @return
   */
  @ResponseBody
  @RequestMapping("/videoCallback")
  @Deprecated
  public String videoCallback(HttpServletRequest req) {
    ResultBean resultBean = new ResultBean();
    Map map = HttpUtils.initParam(req, Map.class);
    try {
      String  jobId = MapUtils.getStrValue(map, "jobId", "");
      String pathTrans = MapUtils.getStrValue(map, "pathTrans", "");
      if (StringUtil.isBlank(jobId) || StringUtil.isBlank(pathTrans)) {
        resultBean.setMsg("jobId or pathTrans  is null");
        resultBean.setCode(ResultCode.ParamException.get_code());
      } else {

        dynamicLocalService.videoCallback(jobId, pathTrans);
        resultBean.setMsg(ResultCode.SUCCESS.getMsg());
        resultBean.setCode(ResultCode.SUCCESS.get_code());

      }
    } catch (Exception e) {
      resultBean.setMsg("网络异常请重试");
      resultBean.setCode(ResultCode.UNSUCCESS.get_code());
    }
    return JSON.toJSONString(resultBean);
  }

  /**
   * 主播俱乐部头部信息
   *
   * @param po
   * @return
   */
  @ResponseBody
  @RequestMapping("/listAnchorClubIndex")
  public String listAnchorClubIndex(HttpServletRequest req) {
    Map<String, Object> map = Maps.newHashMap();
    // start
    Map<String, String> mapOther = HttpUtils.initParam(req, Map.class);
    // 主播ID
    try {
      String userId = MapUtils.getStrValue(mapOther, "userId", "");
      String currentUserId = MapUtils.getStrValue(mapOther, "currentUserId", "");

      if (org.apache.commons.lang3.StringUtils.isBlank(userId)) {
        map.put("code", ResultCode.UNSUCCESS.get_code());
        map.put("msg", "userId is null");
        return JSON.toJSONString(map);
      }
      int type = 0;
      if (!org.apache.commons.lang3.StringUtils.isBlank(currentUserId)) {
        type = watchLocalService.getWatchRelationByUserId(currentUserId, userId);
      }
      // end
      map.put("code", ResultCode.SUCCESS.get_code());
      map.put("msg", "成功");

      LivingRoomInfoVo live = liveRoomLocalService.getLiveRoom(userId);
      map.put("fans", dynamicLocalService.listFans(userId));
      map.put("user", dynamicLocalService.getDynaUser(userId));
      map.put("isFollow", type);
      LiveRoom liveRoom = liveRoomLocalService.getLiveRoomByUserId(userId);
      map.put("liveStatus", liveRoom == null ? 0 : liveRoom.getStatus());
      map.put("live", live == null ? new LivingRoomInfoVo() : live);
    } catch (Exception e) {
      e.printStackTrace();
      logger.error("主播俱乐部头部信息获取失败");
    }
    return JSON.toJSONString(map);
  }

  /**
   * 详情
   *
   * @return
   */
  @SuppressWarnings({ "rawtypes", "unchecked" })
  @RequestMapping(value = "/getshareWords", method = RequestMethod.GET)
  @ResponseBody
  public String shareLive(HttpServletRequest request) {
    ResultBean resultBean = new ResultBean();
    Map map = Maps.newHashMap();
    try {
      map.put("shareWordsForBefore", liveRoomLocalService.getshareWordsForBefore());
      map.put("shareWordsForAfter", liveRoomLocalService.getshareWordsForAfter());
      resultBean.setData(map);
      resultBean.setCode(ResultCode.SUCCESS.get_code());
    } catch (Exception e) {
      e.printStackTrace();
    }
    return JSON.toJSONString(resultBean);

  }

  /**
   * 删除相册
   *
   * @return
   */
  @RequestMapping("/deleteAlbum")
  @ResponseBody
  public String deleteAlbum(HttpServletRequest req) {
    // start
    ResultBean resultBean = new ResultBean();
    String userId = req.getParameter("consume");
    Map mapOther = HttpUtils.initParam(req, Map.class);
    try {

      String picId = MapUtils.getStrValue(mapOther, "picId", "");
      String messageId = MapUtils.getStrValue(mapOther, "messageId", "");
      // end
      if (StringUtil.isBlank(picId) || StringUtil.isBlank(messageId)) {
        resultBean.setCode(ResultCode.UNSUCCESS.get_code());
        resultBean.setMsg("picId or messageId is null");
        return JSON.toJSONString(resultBean);
      }

      DynamicAlbum dynamicAlbum = new DynamicAlbum();
      dynamicAlbum.setMsgId(Integer.valueOf(messageId));
      dynamicAlbum.setPicId(picId);
      dynamicAlbum.setUserId(userId);
      if (dynamicLocalService.deleteAlbumByParams(dynamicAlbum) == 4) {
        resultBean.setCode(ResultCode.UNSUCCESS.get_code());
        resultBean.setMsg("图片不属于你");
        return JSON.toJSONString(resultBean);

      }
      if (dynamicLocalService.checkLast(messageId) < 1) {
        Message mes = new Message();
        mes.setUserId(userId);
        mes.setMessageId(Integer.valueOf(messageId));
        mes.setMessageType("2");
        dynamicLocalService.deleteMessage(mes);
        resultBean.setCode(ResultCode.SUCCESS.get_code());
        resultBean.setMsg("删除成功");
        return JSON.toJSONString(resultBean);
      }
      resultBean.setCode(ResultCode.SUCCESS.get_code());
      resultBean.setMsg("");
    } catch (Exception e) {
      resultBean.setCode(ResultCode.UNSUCCESS.get_code());
      resultBean.setMsg("");
    }
    return JSON.toJSONString(resultBean);

  }

  /**
   * 第一次进入俱乐部推荐明星弹窗
   *
   * @param req
   * @return
   */
  @RequestMapping(value = "/recommendAnchorFirst", method = RequestMethod.GET)
  @ResponseBody
  public String recommendAnchorFirst(HttpServletRequest req) {
    ResultBean resultBean = new ResultBean();
    Map map = HttpUtils.initParam(req, Map.class);
    try {
      String userId = MapUtils.getStrValue(map, "userId", "");
      if (StringUtil.isBlank(userId)) {
        resultBean.setCode(ResultCode.UNSUCCESS.get_code());
        resultBean.setMsg("userId is null");
        return JSON.toJSONString(resultBean);
      }
      resultBean.setCode(ResultCode.SUCCESS.get_code());
      resultBean.setMsg(ResultCode.SUCCESS.getMsg());
      resultBean.setData(userLocalService.recommendAnchorFirst(userId));
    } catch (Exception e) {
      e.printStackTrace();
      resultBean = new ResultBean(ResultCode.UNSUCCESS);
    }
    return JSON.toJSONString(resultBean);
  }

  /**
   * 正文
   *
   * @param req
   * @return
   */
  @RequestMapping(value = "/getMessage", method = RequestMethod.GET)
  @ResponseBody
  public String getMessage(HttpServletRequest req) {
    ResultBean resultBean = new ResultBean();
    try {
      Map mapOther = HttpUtils.initParam(req, Map.class);

      String messageId = MapUtils.getStrValue(mapOther, "messageId", "");
      String userId = HttpUtils.getParam(req, "consume", "");

      logger.info("查询动态数据为空messageId={}", mapOther);
      if (StringUtils.isEmpty(messageId) || StringUtils.isEmpty(userId) ) {
        resultBean.setCode(ResultCode.UNSUCCESS.get_code());
        resultBean.setMsg("messageId or userId is null");
        return JSON.toJSONString(resultBean);
      }
      logger.info("查询动态数据为空messageId={},userId={}", messageId,userId);
      resultBean.setData(dynamicLocalService.getMessageById(messageId, userId));
      resultBean.setCode(ResultCode.SUCCESS.get_code());
      resultBean.setMsg("成功");
      logger.info("查询动态数据为空messageId={}", resultBean);
    } catch (Exception e) {
      e.printStackTrace();
      resultBean = new ResultBean(ResultCode.UNSUCCESS);
    }
    return JSON.toJSONString(resultBean);
  }

  /**
   * 主播俱乐部感兴趣的主播
   *
   * @param req
   * @return
   */
  @RequestMapping(value = "/recommendMesStarClubFor", method = RequestMethod.GET)
  @ResponseBody
  public String recommendMesStarClubFor(HttpServletRequest req) {
    ResultBean resultBean = new ResultBean();
    try {

      Map mapOther = HttpUtils.initParam(req, Map.class);
      String userId = MapUtils.getStrValue(mapOther, "userId", "");

      if (StringUtils.isEmpty(userId)) {
        resultBean.setCode(ResultCode.UNSUCCESS.get_code());
        resultBean.setMsg("userId is null");
        return JSON.toJSONString(resultBean);
      }

      Page po = new Page();
      po.setPageSize(3);
      List list = dynamicLocalService.recommendMesStarClubFor(userId);
      logger.info("userId={}俱乐部感兴趣的主播={}", userId, list);
      if (list.size() == 0) {
        list = userLocalService.recommendStarClub(po, userId).getResult();
      }
      resultBean.setData(list);
      resultBean.setCode(ResultCode.SUCCESS.get_code());
      resultBean.setMsg("成功");
    } catch (Exception e) {
      e.printStackTrace();
      resultBean = new ResultBean(ResultCode.UNSUCCESS);
    }
    return JSON.toJSONString(resultBean);
  }

}
